import serial
import sys
import time

def send_at_command(ser,command):

    if not ser.is_open:
        print("串口未打开")
        return
    ser.write((command + '\r\n').encode())
    ser.flush()
    #time.sleep(1)
    # 读取并打印回应
    while True:
        #response = ser.readline().decode().strip()
        response = ser.read_all().decode().strip()
        if response:
            print(response)
        else:
            break

def main():
    if len(sys.argv) != 3:
        print("使用方法: python script.py 串口号 波特率")
        sys.exit(1)

    port = sys.argv[1]
    baudrate = int(sys.argv[2])

    try:
        with serial.Serial(port=port, baudrate=baudrate, timeout=1) as ser:
            print(f"串口{port}已成功打开，波特率为{baudrate}")

            commands = ["AT+CGMR", "AT^CPMODE?", "AT+IPR?", "AT+IPR=115200", "AT+IPR?"]
            for cmd in commands:
                send_at_command(ser, cmd)
                if cmd == "AT+IPR=115200":
                    time.sleep(3)  # 如果更改了波特率，可能需要等待模块重新配置
    except serial.SerialException as e:
        print(f"串口{port}无法打开: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()
